package com.coolbi.security.web.action;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.coolbi.common.web.action.BaseAction;
import com.coolbi.security.biz.RolesBiz;
import com.coolbi.security.entity.Roles;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

public class RolesAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private Roles roles;
	private List<Roles> rolesList;

	@Autowired
	private RolesBiz rolesBiz;

	public void setRolesBiz(RolesBiz rolesBiz) {
		this.rolesBiz = rolesBiz;
	}

	/** 添加角色 */
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "roles.name", message = "角色名称必填"),
			@RequiredStringValidator(fieldName = "roles.authority", message = "角色标签必填"),
			@RequiredStringValidator(fieldName = "roles.description", message = "角色描述必填") })
	public String addRoles() throws Exception {
		roles = rolesBiz.save(roles);
		return SUCCESS;
	}

	/** 删除角色 */
	public String delete() throws Exception {
		rolesBiz.delete(roles.getId());
		return SUCCESS;
	}

	/** 根据ID查询角色信息 */
	public String findRolesById() throws Exception {
		roles = rolesBiz.get(roles.getId());
		return SUCCESS;
	}

	/** 修改角色 */
	public String updateRoles() throws Exception {
		rolesBiz.update(roles);
		return SUCCESS;
	}

	/** 分页查看所有角色 */
	public String listByPage() throws Exception {
		pager.setRecordCount(rolesBiz.count());
		rolesList = rolesBiz.list((pager.getCurrPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
		return SUCCESS;
	}

	/**
	 * 生成角色树
	 * @return
	 * @throws Exception
	 */
	public String listTree() throws Exception {
		rolesList = rolesBiz.list();
		return SUCCESS;
	}
	
	/**
	 * 检测角色名称是否已存在
	 * @return
	 */
	public String checkRoleName() {
		try {
			boolean flag = false;
			if (null == roles.getId()) {
				flag = rolesBiz.checkRoleName(roles.getName());
			}
			return ajax(String.valueOf(!flag));
		} catch (Exception e) {
			e.printStackTrace();
			return ajax("error");
		}
	}
	
	/**
	 * 检测权限标签是否已存在
	 * @return
	 */
	public String checkAuthority() {
		try {
			boolean flag = false;
			if (null == roles.getId()) {
				flag = rolesBiz.checkAuthority(roles.getAuthority());
			}
			return ajax(String.valueOf(!flag));
		} catch (Exception e) {
			e.printStackTrace();
			return ajax("error");
		}
	}
	
	public List<Roles> getRolesList() {
		return rolesList;
	}

	public void setRolesList(List<Roles> rolesList) {
		this.rolesList = rolesList;
	}

	public Roles getRoles() {
		return roles;
	}

	public void setRoles(Roles roles) {
		this.roles = roles;
	}

}
